import boto3
import sys
import time
import datetime


client = boto3.client('elbv2')

# parameter

tga = sys.argv[1]
hostid = sys.argv[2]
hostport = int(sys.argv[3])

# shell

def register(tga, hostid, hostport):
    register_targets = client.register_targets(
        TargetGroupArn=tga,
        Targets=[
            {
                'Id': hostid,
                'Port': hostport,
            },
        ],
    )
    print(register_targets)

def getTargetHealth(tga, hostid, hostport):
    response = client.describe_target_health(
        TargetGroupArn=tga,
        Targets=[
            {
                'Id': hostid,
                'Port': hostport,
            },
        ],
    )

    health = response['TargetHealthDescriptions'][0]['TargetHealth']['State']
    return health


if __name__ == "__main__":

    # parameter

    tga = sys.argv[1]
    hostid = sys.argv[2]
    hostport = int(sys.argv[3])

    register(tga, hostid, hostport)

    health_status = getTargetHealth(tga, hostid, hostport)
    check_count= 0
    if hostport == 6311:
        while health_status != 'healthy' and check_count < 500:
            check_count += 1
            time.sleep(1)
            health_status = getTargetHealth(tga, hostid, hostport)

            print("ELB切换完成，当前时间：{}，ELB状态查询次数：{}，当前ELB状态：{}".format(datetime.datetime.now(), check_count, health_status))
    else:
        while health_status != 'healthy' and check_count < 150:
            check_count += 1
            time.sleep(1)
            health_status = getTargetHealth(tga, hostid, hostport)

            print("ELB切换完成，当前时间：{}，ELB状态查询次数：{}，当前ELB状态：{}".format(datetime.datetime.now(), check_count, health_status))

